package com.gdut.huayan.controller;

import com.gdut.huayan.entity.dto.Result;
import com.gdut.huayan.service.exception.BaseException;
import com.gdut.huayan.utils.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result serverErrorExceptionHandler(Exception e) {
        e.printStackTrace();
        Result result = new Result();
        result.setCode(500);
        result.setMessage("系统错误，请联系管理员");
        return result;
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        e.printStackTrace();
        Result result = new Result();
        result.setCode(405);
        result.setMessage("您所请求的方法不被系统允许");
        return result;
    }

    @ExceptionHandler(IOException.class)
    public Result baseExceptionHandler(IOException e) {
        e.printStackTrace();
        Result result = new Result();
        result.setCode(501);
        result.setMessage("系统IO出错，请联系管理员");
        return result;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handlerNoFoundException(NoHandlerFoundException e) {
        e.printStackTrace();
        Result result = new Result();
        result.setCode(404);
        result.setMessage("您访问的路径不存在，系统未找到资源");
        return result;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Result result = new Result();
        result.setCode(4000);
        result.setMessage("输入参数错误");
        Map<String, String> errorMessage = new HashMap<>();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            if (StringUtils.isNotEmpty(fieldError.getDefaultMessage())) {
                errorMessage.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
        }
        result.setData(errorMessage);
        return result;
    }


    @ExceptionHandler(BaseException.class)
    public Result baseExceptionHandler(BaseException baseException) {
        Result result = new Result();
        result.setCode(baseException.getCode());
        result.setMessage(baseException.getUserMessage());
        return result;
    }



}
